<?php

namespace App\Console\Commands;

use App\Repositories\Eloquent\FinanceBillRepository;
use Illuminate\Console\Command;

class UpdateBillCurAvailable extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'bills:update-asset';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @param \App\Repositories\Eloquent\FinanceBillRepository $billRepository
     *
     * @return mixed
     */
    public function handle(FinanceBillRepository $billRepository)
    {
        //
        $bills = $billRepository->orderBy('created_at', 'asc')->get(['id', 'bill_uid', 'bill_amt', 'cur_available', 'bill_type']);
        $uBills = $bills->groupBy('bill_uid');
        $batchUpdate = [];
        foreach ($uBills as $key => $uBill) {
            $available = 0;
            foreach ($uBill as $bill) {
                if ($bill->bill_type == 2) {
                    $available = bcadd($available, $bill->bill_amt, 6);
                } elseif ($bill->bill_type == 1) {
                    $available = bcsub($available, $bill->bill_amt, 6);
                }
                $batchUpdate[$bill->id] = [
                    'cur_available' => $available
                ];
            }
        }
        batchUpdateById($batchUpdate, 'finance_bills');
    }
}
